package com.gmall.seckill.service;

import com.gmall.model.seckill.SeckillGoods;
import com.gmall.seckill.common.RedisConst;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 预热
 * 每天晚上0：00 ，查询出7天后将要开始秒杀的商品，将商品的库存数量加载到redis中
 */
@Service
public class SecKillDB2RedisService {

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    SecKillGoodsService secKillGoodsService;


    //@Scheduled(cron = "0/10 * * * * ?")
    @XxlJob("loadGoods2Redis")
    public void loadGoods2Redis(){

        //1、查询出7天后的秒杀商品
        //2、将商品列表保存到Redis中(没有排序)，Hash 大Key SecKillGoods
        //                                     小key skuID--->value:SecKillGoods

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(simpleDateFormat.format(new Date()) + " loadGoods2Redis");
        redisTemplate.delete(RedisConst.SEC_KILL_REDIS_KEY);//之前预热的删除
        //获取7天后的秒杀的商品
        List<SeckillGoods> secKillGoodsList = secKillGoodsService.findSecKillGoodsListAfter(7);
        //保存到Redis中
        secKillGoodsList.forEach(secKillGoods ->{
            redisTemplate.opsForHash().put(RedisConst.SEC_KILL_REDIS_KEY,
                    String.valueOf(secKillGoods.getSkuId()),secKillGoods);
            redisTemplate.opsForValue().set(RedisConst.SEC_KILL_REDIS_STOCK_COUNT_KEY + secKillGoods.getSkuId(),secKillGoods.getStockCount());
        });
    }

}
